<?php
namespace control;
/*
*宿舍档案类
*/

class dormitoryClass extends adIndexClass
{
    private const page = 'dormitory';
    private const table = 'dormitory';
    private const title = '宿舍档案';
    public array $stateOption = ['启用', '维护中', '停用'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '宿舍编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'building' => [
                        'name'  => "楼号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'floor'  => [
                        'name'  => "楼层",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'room'         => [
                        'name'  => '宿舍号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '类别',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'maxPeople'          => [
                        'name'  => '可住人数',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'livePeople'          => [
                        'name'  => '已住人数',
                        'width' => 200,
                    ],
                    'empty'          => [
                        'name'  => '空缺人数',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "宿舍编号" => text(array("name" => "orderNo")),
                    "楼号"     => repeatSelect(array('sqlForm'=>self::table,'sqlField'=>'building','name'=>'building')),
                    '楼层' => repeatSelect(array('sqlForm'=>self::table,'sqlField'=>'floor','name'=>'building')),
                ],
                [
                    '宿舍号'   => repeatSelect(array('sqlForm'=>self::table,'sqlField'=>'room','name'=>'room')),
                    "类别" => select(["name" => "type", 'option' => explode('，', para('dormitoryType'))]),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //全等查询数组
        $equal = array(
            "type" => $this->post('type'),//类别
            "state" => $this->post('state'),//状态
            "room" => $this->post('room'),//宿舍号
            "building" => $this->post('building'),//楼号
        );
        $and = "";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //已住人数
            $livePeople = static::total(array('table'=>'dormitory_record','where'=>" and dormitoryId = '$array[id]' and state = '入住'"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "livePeople":
                        $row[] = $livePeople;
                        break;
                    case "empty":
                        $row[] = $array['maxPeople']-$livePeople;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    public static function mergePower($oldArray, $newArray): array
    {
        if (empty($oldArray) || !is_array($oldArray))
        { return $newArray; }
        if (empty($newArray) || !is_array($newArray))
        { return $oldArray; }

        $powerAll = array_merge_recursive($oldArray, $newArray);

        $data = [];
        foreach ($powerAll as $name => $array) {
            $data[$name] = array_values(array_unique($array));
        }

        return $data;
    }
    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "楼号：" => text(["name" => "building", 'class' => 'text', "value" => $info['building']]),
                    must . "楼层：" => text(["name" => "floor", 'class' => 'text', "value" => $info['floor']]),
                ],
                [
                    must . "宿舍号：" => text(["name" => "room", 'class' => 'text', "value" => $info['room']]),
                    must . "类别：" => select(["name" => "type", 'title'=>'类别','class' => 'text', 'option' => explode('，', para('dormitoryType')), "value" => $info['type']]),
                ],
                [
                    must . "可住人数：" => text(["name" => "maxPeople", 'class' => 'text', "value" => $info['maxPeople']]),
                    "面积：" => text(["name" => "area", 'class' => 'text', 'unit' => '㎡', "value" => $info['area']]),
                ],
                [
                    must . "月租：" => text(["name" => "rent", 'class' => 'text', 'unit' =>  static::$unit , "value" => $info['rent']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'building' => $this->post('building'),
            'floor' => $this->post('floor'),
            'room' => $this->post('room'),
            'type' => $this->post('type'),
            'maxPeople' => $this->post('maxPeople'),
            'area' => $this->post('area'),
            'rent' => $this->post('rent'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'building' => '楼号',
            'floor' => '楼层',
            'room' => '宿舍号',
            'type' => '类别',
            'maxPeople' => '可住人数',
            'rent' => '月租',
        ];
        $rules = [
            'building' => 'required',
            'floor' => 'required',
            'room' => 'required',
            'type' => 'required',
            'maxPeople' => 'required',
            'rent' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,'where'=>"building = '$field[building]' and floor = '$field[floor]' and room = '$field[room]' and id !='$id'")) >0){
            $json['warn'] = '已存在此宿舍号';
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'DOM',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '启用',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            $_SESSION[self::page]['id'] = $info['id'];
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                switch ($info['state']){
                    case '停用':
                        $firState = '启用';
                        $secState = '维护中';
                        $titleOne = '启用';
                        $titleTwo = '维护';
                        break;
                    case '维护':
                        $firState = '启用';
                        $secState = '停用';
                        $titleOne = '启用';
                        $titleTwo = '停用';
                        break;
                    default:
                        $firState = '停用';
                        $secState = '维护中';
                        $titleOne = '停用';
                        $titleTwo = '维护';
                        break;
                }
                //按钮
                $button[] = [
                    "name" => $titleOne,
                    "type" => "点击事件",
                    "cla" => $this->get('cla'),
                    "fun" => "layer('{$this->get('cla')}','stateSwitch',{type:'{$firState}', id:'{$info['id'] }'})",
                ];
                //按钮
                $button[] = [
                    "name" =>$titleTwo,
                    "type" => "点击事件",
                    "cla" => $this->get('cla'),
                    "fun" => "layer('{$this->get('cla')}','stateSwitch',{ type:'{$secState}',id:'{$info['id'] }'})",
                ];
            }
            if ($this->power(self::page,'del')){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $livePeople = static::total(array('table'=>'dormitory_record','where'=>"dormitoryId = '".$info['id']."' and state = '入住'"));
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "楼号" => $info['building'],
                        "宿舍号" => $info['room'],
                        "类别" => $info['type'],
                        "可住人数" => $info['maxPeople'],
                    ),
                    array(
                        "已住人数" => $livePeople,
                        "空缺人数" => $info['maxPeople']-$livePeople,
                        "面积（㎡）" => $info['area'],
                        "月租(".static::$unit.")" => $info['rent'],
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
                '系统信息' => array(
                    array(
                        "宿舍编号" => $info['orderNo'],
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ),
                    array(
                        "状态" => $info['state'],
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    /**
     * 启用/停用
     */
    public function stateSwitch()
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否更改此宿舍状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit()
    {
        $id = $this->post('id');
        $type = $this->post('type');
        $info = query(self::table," id = '$id'");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = "未找到此宿舍档案";
        } elseif (!in_array($type, $this->stateOption)) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $type,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id ='$id'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$type}】， id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power =$word= '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已复核',
            'checkTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] != '待复核') {
            $json['warn'] = '此采购记录不是待复核状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待复核',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购记录';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此采购记录不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}
